<template>
	<div style="width: 100%;">
		<div class="tabsClass">
			<div class="treesty">
				<blockComponents :msg="'项目阶段'"></blockComponents>
				<el-tree
					:data="dataTree.data"
					node-key="projectStageId"
					default-expand-all
					:expand-on-click-node="false"
					@node-click="handleNodeClick"
				>
					<template #default="{ data }">
						<div class="custom-tree-node d-flex m-l10">
							<el-tooltip
									class="box-item"
									effect="light"
									:disabled="data?.stageName.length<6"
									:content="data.stageName"
									placement="top"
							>
								<div class="stageName">
								<span
										v-if="state.projectStageId == data['projectStageId']"
										style="color: #fc7018"
								>{{ data.stageName }}</span
								>
									<span v-else>{{ data.stageName }}</span>
								</div>
							</el-tooltip>

							<span v-if="state.data.type == 3">
								<span class="projectPeople" @click="append(data)">
									进场人员
								</span>
							</span>
						</div>
					</template>
				</el-tree>
			</div>
			<div style="flex: 1" class="tabBox">
				<div class="flex_project">
				</div>
				<div class="title_sty">
					<div class="big_box_flex">
						<p class="text_height">项目名称</p>
						<p class="p_sty">{{ state.data.projectName }}</p>
					</div>
					<div class="big_box_flex">
						<p class="text_height">项目发起部门</p>
						<p class="p_sty">{{ state.data.responsibleDepartmentName }}</p>
					</div>
					<div class="big_box_flex">
						<p class="text_height">项目时间</p>
						<p class="p_sty">
							{{ state.data.predictStartTime || "0000:00:00" }} 至
							{{ state.data.predictEndTime || "0000:00:00" }}
						</p>
					</div>
				</div>
				<div class="btn_sty">
					<el-tabs
						v-model="state.btnActiveName"
						type="card"
						class="demo-tabs"
						@tab-change="tabHandleClick"
					>
						<el-tab-pane label="表格形式" name="0"></el-tab-pane>
						<el-tab-pane label="甘特图" name="1"></el-tab-pane>
					</el-tabs>

					<div v-if="state.projectStageId">
						<el-button v-show="isShow" @click="upAnddownHandler(-1)" class="button_edit"
							>上移</el-button
						>
						<el-button v-show="isShow" @click="upAnddownHandler(1)" class="button_edit"
							>下移</el-button
						>
						<el-button
							v-show="isShow"
							@click="publicTasksClick()"
              class="button_edit"
							><svg-icon
								icon-class="project-add-icon"
								class="m-r5"
							/>公共任务</el-button
						>
						<el-button
								v-show="isShow"
								@click="departmentTasksClick()"
                class="button_edit"
						><svg-icon
								icon-class="project-add-icon"
								class="m-r5"
						/>招标专属任务</el-button
						>
<!--						部门专属任务-->

						<el-button v-show="isShow" class="button_delete" @click="deleteHandler"
							>删除</el-button
						>
						<el-button v-show="isShow" @click="onExport(getSearch())" class="button_edit"
							><svg-icon icon-class="export" class="m-r5" />导出</el-button
						>
						<el-button v-show="isShow" @click="distributeHandel" class="button_funtion"
							><svg-icon icon-class="pf-task" class="m-r5"/>派发任务</el-button
						>
					</div>
				</div>
				<div class="d-flex">
					<div class="table_sty">
						<tableIndex
							:tableData="state.tableData"
							:tableHead="state.tableHead"
							:isIndex="true"
							:height="500"
							:page="state.page"
							:not-search="true"
							@selectChange="selectChange"
							@page-change="pageChange"
						>
							<template #operate>
								<el-table-column
									label="操作"
									width="200"
									fixed="right"
									align="center"
								>
									<template #default="{ row }">
										<el-button size="small" @click="editHandel(row)" class="button_edit"
											>编辑</el-button
										>
										<el-button
											v-if="getURLhandler(route.path).tabId !== '1'"
											size="small"
                      class="button_edit"
											@click="professionalHandel(row)"
											>工作细项明细</el-button
										>
									</template>
								</el-table-column>
							</template>
						</tableIndex>
					</div>
				</div>
			</div>
			<div class="gantt_sty" v-show="state.btnActiveName == 1">
				<GanttChart
					v-if="state.dateList"
					:ganttList="state.dateList"
					ref="ganttee"
				/>
			</div>
		</div>
	</div>

	<planDialog
			ref="plan"
			@refreshList="
					getPageList({
						projectId: projectId,
						projectStageId: state.projectStageId,
					})
				"
	/>

	<biddingDialog ref="bidding"> </biddingDialog>

	<public-tasks-popup ref="publicTasksPopupRef" @onSuccess="getProjectList(1)"/>
	<department-tasks-popup ref="departmentTasksPopupRef" @onSuccess="getProjectList(1)"/>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from "vue";
import BlockComponents from "@/components/block_components/index.vue";
import {getDiffDay} from "@/common/utils/GlobalUtils";
import { deriveHandelFnc } from "@/hooks/downCommon";
import GanttChart from "./gantt_chart.vue";
import { useRoute, useRouter } from "vue-router";
import {
	projectTask,
	projectTaskApi
} from "@/api/project.js";
import TableIndex from "@/components/table/index.vue";
import PlanDialog from "./w_planDialog.vue";
import BiddingDialog from "./biddingDialog.vue";
import {
	ElTabs,
	ElTree,
	ElTabPane,
	ElMessage,
	ElMessageBox,
	ElButton,
	ElTableColumn,
} from "element-plus";
import { getURLhandler } from "@/views/constructionProjectManage/static/utools.js";
import {ElTooltip} from "element-plus";
import PublicTasksPopup from "@/views/constructionProjectManage/projectPlan/components/publicTasksPopup.vue";
import DepartmentTasksPopup from "@/views/constructionProjectManage/projectPlan/components/departmentTasksPopup.vue";


const route = useRoute();
const projectId = getURLhandler(route.path).id;
const isDark = getURLhandler(route.path).isDark;
const props = defineProps({
	isShow: {
		type: Boolean,
		default: true,
	},
});


const questForm = reactive({taskChooseType:''});
const state = reactive({
	stage:{},
	allTaskList: [],
	isZb: true,
	treeNode: null, //树节点
	departmentPersonList: [],
	allDepartmentList: [],
	tableList: [],
	projectStageId: "",
	data: {
		projectName: "",
		predictStartTime: "",
		predictEndTime: "",
		responsibleDepartmentName: "",
	},
	dateList: [],
	btnActiveName: "0",
	ganttList: [{}],
	tableData: [],
	tableHead: [
		{
			prop: "status",
			label: "任务状态",
			formatter: (row) => {
				let str = "";
				// -1未完成0进行中1完成2已停工
				switch (row.status) {
					case -2:
						str = "待配置";
						break;
					case -1:
						str = "未开始";
						break;
					case 0:
						str = "进行中";
						break;
					case 1:
						str = "完成";
						break;
				}
				return str;
			},
			width: "100",
		},
		{
			prop: "isEffect",
			label: "是否派发",
			width: "110",
			formatter: (row) => {
				return ['否','是'][row.isEffect] ?? '-';
			}
		},
		{
			prop: "taskName",
			label: "实施任务名称",
			width: "110",
		},
		{
			prop: "projectTaskId",
			label: "任务编号",
			width: "100",
		},
		{
			prop: "taskType",
			label: "任务类型",
			formatter: (row) => {
				let str = "";
				switch (row.taskType) {
					case 1:
						str = "部门专属任务";
						break;
					case 2:
						str = "公共任务";
						break;

					default:
						str = "-";
						break;
				}
				return str;
			},
			width: "100",
		},
		// {
		// 	prop: "planStartTime",
		// 	label: "计划开始时间",
		// 	width: "160",
		// },
		// {
		// 	prop: "planEndTime",
		// 	label: "计划完成时间",
		// 	width: "160",
		// },
		{
			prop: "responsibleDepartmentName",
			label: "责任部门",
			width: "100",
		},
		{
			prop: "responsibleUserName",
			label: "责任人",
			width: "100",
		},
	],
	page: {
		page: 1,
		pageSize: 50,
		total: 0,
	},
});
let router = useRouter();
const getSearch = () => {
	return {
		projectStageId: state.projectStageId,
		projectId: projectId,
	};
};
const exportConfig = reactive({
	fileName: "项目任务",
	apiPath: "taskExport",
	form: {},
});
const titleName = ref("");
const visible = ref(false);
const publicTasksPopupRef = ref(null);
const departmentTasksPopupRef = ref(null);


// 编辑
const editHandel = (row) => {
	/*titleName.value = "编辑";
	visible.value = true;
	let params = {
			...row,
			projectStageId: state.projectStageId,
			projectName: state.data.projectName,
			projectId: state.data.projectId,
	}
	if(!row.taskChooseType){
		params.taskChooseType = '';
	}
	for (let key in params){
		questForm[key] = params[key];
	}

	questForm.time = [row.planStartTime, row.planEndTime];*/

	let params = {
		...row,
		projectStageId: state.projectStageId,
		projectName: state.data.projectName,
		projectId: state.data.projectId,
		time:[row.planStartTime+' 00:00:00', row.planEndTime+' 00:00:00']
	}

	switch (row.taskType) {
		case 1: // 部门任务
			departmentTasksPopupRef.value.openPopup('编辑',state,params);
			break;
		case 2: // 公共任务
			publicTasksPopupRef.value.openPopup('编辑',state,params);
			break;
	}

};

// 工作明细
const professionalHandel = (row) => {
	router.push({
		path: `/constructionProjectManage/preliminaryProject/components/nodeProject/projectTaskId=${row.projectTaskId}&projectId=${projectId}&projectStageId=${state.projectStageId}`,
	});
};


const { onExport } = deriveHandelFnc(exportConfig);

const defaultProps = {
	children: "children",
	label: "label",
};
let dataTree = reactive([]);
const ganttee = ref(null);
const plan = ref(null);
const bidding = ref(null);

const handleNodeClick = (data, node, treeNode, event) => {
	state.stage = data;
	state.projectStageId = data.projectStageId;
	getPageList({
		projectId: projectId,
		projectStageId: data.projectStageId,
	});
	getAactiveDepartmentTask(data.projectStageId);
};

//获取当前阶段公共任务
const getAactiveDepartmentTask = (stageId) => {
	projectTaskApi.getStageAllTask(stageId).then((res) => {
		const { code, data, msg } = res;
		if (code === '200') {
			state.allTaskList = data;
		}
	});
};

//获取表格数据
const getPageList = (e) => {
	let obj = {
		pageNum: state.page.page,
		pageSize: state.page.pageSize,
		param: {
			projectId: e.projectId,
			projectStageId: e.projectStageId,
		},
	};
	projectTask.getProjectTaskPage(obj).then((res) => {
		if (res.code === '200') {
			console.log(res.data);
			state.tableData = res.data.content;
			state.page.total = res.data.totalSize;

			state.dateList = [];
			res.data.content.forEach((v) => {
				const obj = {
					// taskName: state.taskNamev,
					text: v.taskName,
					// nodeName: v.actionResult,
					duration: getDiffDay(v.planStartTime, v.planEndTime),
					end_date: new Date(v.planEndTime),
					start_date: new Date(v.planStartTime),
				};
				if (getDiffDay(v.planStartTime, v.planEndTime) !== 0) {
					state.dateList.push(obj);
				}
			});
			nextTick(() => {
				ganttee.value.clearHandler();
				ganttee.value.init();
			});
		}
	});
};

const tabHandleClick = (data) => {
	switch (state.btnActiveName) {
		case "0":
			break;
		case "1":
			break;
	}
};

const pageChange = (e) => {
	state.page.page = e.page;
	state.page.pageSize = e.limit;

	getPageList({
		projectId: projectId,
		projectStageId: state.projectStageId,
	});
};

const getListPage = (type) => {

	projectTask.getStageDetail(projectId || "").then((res) => {
		if (res.code === '200') {
			Object.assign(dataTree, {
				data: res.data.stageVo.stages,
			});
			if(!type){
				state.projectStageId = res.data.stageVo.stages?.[0]?.projectStageId;
				state.stage = res.data.stageVo.stages?.[0];
			}
			if(state.projectStageId){
				getAactiveDepartmentTask(state.projectStageId);
				getPageList({
					projectId: projectId,
					projectStageId: state.projectStageId,
				});
			}
			state.data = res.data;
		}
	});
};

//获取阶段树
const getProjectList = (type) => {
	getListPage(type);
};

//上移 下移
const upAnddownHandler = (val) => {
	if (state.tableList.length === 0) {
		return ElMessage.warning("请先选择需要移动的数据");
	} else {
		let obj = {
			projectTaskId: state.tableList[0].projectTaskId,
			oldTaskOrder: state.tableList[0].taskOrder,
			projectStageId: state.projectStageId,
			orderNum: 1,
			updateOrderType: val,
		};
		projectTask.updateTaskOrder(obj).then((res) => {
			if (res.code === '200') {
				ElMessage.success("操作成功");
				getPageList({
					projectId: projectId,
					projectStageId: state.projectStageId,
				});
			}
		});
	}
};

//新增
const addHandler = () => {
	if (!state.projectStageId) return ElMessage.warning("请先选择阶段");
	plan.value.state.centerDialogVisible = true;
	plan.value.state.type = 0;
	plan.value.state.projectId = projectId || "";
	plan.value.state.projectStageId = state.projectStageId;
};

//编辑
const updateHandler = () => {
	if (state.tableList.length === 0) {
		return	ElMessage.warning("请先选择需要编辑的数据");
	} else {
		plan.value.state.type = 1;
		plan.value.state.projectId = projectId || "";
		plan.value.state.projectStageId = state.projectStageId;

		for (let key in state.tableList[0]) {
			plan.value.formInline[key] = state.tableList[0][key];
		}
		plan.value.state.centerDialogVisible = true;
	}
};

//表格选中内容
const selectChange = (val) => {
	state.tableList = val;
};

//删除
const deleteHandler = () => {
	if (state.tableList.length === 0) {
		return ElMessage.warning("请先选择需要删除的数据");
	} else {
		ElMessageBox.confirm("确认删除吗?", {
      confirmButtonText: "确认",
      confirmButtonClass: "button_view",
      cancelButtonText: "取消",
      cancelButtonClass:"button_cancel2",
			type: "warning",
		})
			.then(() => {
				projectTask.removeTask(state.tableList[0].projectTaskId).then((res) => {
					if (res.code === "200") {
						ElMessage.success("删除成功");
						getPageList({
							projectStageId: state.projectStageId,
							projectId: projectId,
						});
					}
				});
			})
			.catch(() => {});
	}
};

const append = (data) => {
	router.push({
		path: `/constructionProjectManage/preliminaryProject/components/approachPeople/projectId=${projectId}&projectStageId=${data.projectStageId}`,
	});
};

// 派发任务
const distributeHandel = () => {
	if(!state.tableList.length){
		return ElMessage.warning('请选择需要派发的任务!');
	}
	/*	let list = JSON.parse(JSON.stringify(state.tableData)).map(
			(item) => item.projectTaskId
		);*/

		let list = JSON.parse(JSON.stringify(state.tableList)).map(
		(item) => item.projectTaskId
	);
	projectTask.effectTask({ projectTaskIds: list }).then((res) => {
		if (res.code === "200") {
			ElMessage.success("操作成功");
			getListPage(1);
		}
	});
};

/**
 * 公共任务
 */
const publicTasksClick = () => {
	let stage = state.stage;
	publicTasksPopupRef.value.openPopup('创建',{...state,stageName:stage.stageName,predictStartTime:stage.predictStartTime,predictEndTime:stage.predictEndTime});
}

/**
 * 部门专属任务
 */
const departmentTasksClick = () => {
	let stage = state.stage;
	departmentTasksPopupRef.value.openPopup('创建',{...state,stageName:stage.stageName,predictStartTime:stage.predictStartTime,predictEndTime:stage.predictEndTime});
}

onMounted(() => {
	 getProjectList();
});
</script>
<style lang="scss" scoped>
@import "@/views/constructionProjectManage/static/button.scss";
.stageName{
	width:70px;
	overflow:hidden;
	white-space: nowrap;
	text-overflow: ellipsis;
	-o-text-overflow:ellipsis;
}

.tabsClass {
	display: flex;
	// overflow-x: scroll;
	overflow-x: auto;
  width: 100%;
	.treesty {
		min-width: 13%;
		margin-right: 34px;
	}
	.tabBox {
		min-width: 84%;
	}
}

.oneline {
	.el-form-item {
		width: 50%;
	}
}
.flex_project {
	display: flex;
	align-items: center;
	.info {
		font-size: 16px;
		font-family: SourceHanSansCN-Medium, SourceHanSansCN;
		font-weight: 500;
		color: #7d7d9a;
		line-height: 24px;
		margin-right: 10px;
	}
	.hint {
		// width: 582px;
		padding-left: 10px;
		padding-right: 10px;
		height: 34px;
		border-radius: 17px;
		line-height: 34px;
		border: 1px solid #d4ae85;
		text-align: center;
	}
}
.color_sty {
	color: #ff7b50;
	cursor: pointer;
}
.title_sty {
	display: flex;
	font-size: 14px;
	justify-content: space-between;
	.big_box_flex {
		display: flex;
		.text_height {
			line-height: 40px;
		}
		.p_sty {
			margin-left: 20px;
			width: 300px;
			padding-left: 10px;
			height: 40px;
			line-height: 40px;
			background: #f7f7fa;
			border-radius: 4px;
		}
	}
}
.btn_sty {
	display: flex;
	justify-content: space-between;
	margin-top: 20px;
	.el-button {
		margin-left: 20px;
	}
}
.projectPeople {
	color: #fff;
	cursor: pointer;

	text-align: center;
	font-size: 12px;
	height: 20px;

	line-height: 20px;
	margin-left: 20px;
	background-color: #d4ae85;
	border-radius: 10px;
	padding-left: 5px;
	padding-right: 5px;
}
.gantt_sty {
	// height: 500px;
	margin-top: 200px;
	// width: 500px;
	margin-left: 20px;
}

.el-form-item,
.el-select {
	width: 100% !important;
}
</style>
